package cn.fotoit.product.system.service;

import cn.fotoit.product.rule.PermissionType;
import cn.fotoit.product.rule.RoleType;
import cn.fotoit.product.system.entity.Permission;
import cn.fotoit.product.system.entity.Role;
import cn.fotoit.product.system.entity.RoleRelPermission;
import cn.fotoit.product.system.entity.User;
import cn.fotoit.product.system.repository.PermissionRepository;
import cn.fotoit.product.system.repository.RoleRelPermissionRepository;
import cn.fotoit.product.system.repository.RoleRepository;
import cn.fotoit.product.system.repository.UserRepository;
import cn.fotoit.product.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 初始化数据库用，后期删除
 */
@Service
public class IoService {


    @Autowired
    private PermissionRepository permissionRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRelPermissionRepository roleRelPermissionRepository;

    //添加数据库的用户角色和资源数据
    public void addPermissions() throws IllegalAccessException {


        List<Permission> permissions = new ArrayList<>();


        Field[] fields = PermissionType.class.getFields();
        for (int i = 0; i < fields.length; i++) {
            Permission permission = new Permission();
            permission.setId(i + 1);
            permission.setDeleted(false);
            permission.setName(fields[i].get(PermissionType.class).toString());
            permission.setPermissionKey(fields[i].getName());
            permission.setRemark(fields[i].get(PermissionType.class) + "(核心，请勿修改)");
            permissionRepository.save(permission);
            permissions.add(permission);
        }


        Role role1 = new Role();
        role1.setId(1);
        role1.setName(RoleType.system_super_admin);
        role1.setRoleKey("system_super_admin");
        role1.setRemark("拥有所有权限");
        roleRepository.save(role1);

        for (Permission permission : permissions) {
            RoleRelPermission roleRelPermission = new RoleRelPermission();
            roleRelPermission.setRoleId(1);
            roleRelPermission.setPermissionId(permission.getId());
            roleRelPermissionRepository.save(roleRelPermission);
        }


        User user = new User();
        user.setIsLock(false);
        user.setId(1);
        user.setLoginName("admin");
        user.setLoginPassword(PasswordUtil.getPasswordByUsernameAndPassword("admin", "123"));
        user.setNickName("hhh");
        user.setRoleId(1);//数据库中的第一条记录
        userRepository.save(user);


    }


}
